package com.lwh.videopicplayer.view;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.xutils.common.Callback;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.lwh.videopicplayer.PlayActivity;
import com.lwh.videopicplayer.R;
import com.lwh.videopicplayer.utils.Utils;

import static android.content.Context.WINDOW_SERVICE;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @author zj 　2020/4/20
 * 作用:使用底层播放器　封装一个可以播放mp3/图片   mp4 的view
 */
public class PicandVideo extends RelativeLayout {
    ImageView iv;
    SurfaceView sv;
    Surface mSurface;

    boolean surfaceInited = false;

    ImageView pic;
    TextView text;

    ImageView smallImage;

    Context mContext;

    PlayActivity.MainHandler mainHandler;

    WindowManager mWindowManager;
    private LayoutParams mTextParams;
    private LayoutParams mSmallImgParams;

    ImageOptions imageOptions;

    MediaPlayer mediaPlayer;
    MediaPlayer videomediaPlayer;
    static String filepath = "";
    int needSeekTime = 0;

    int screenWidth = 0;
    int screenHeight = 0;

    public PicandVideo(Context context) {
        this(context, null);
    }

    public PicandVideo(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PicandVideo(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;

        View root = inflate(context, R.layout.picvideo, this);
        iv = (ImageView) root.findViewById(R.id.iv);
        sv = (SurfaceView) root.findViewById(R.id.sv);
        pic = (ImageView) root.findViewById(R.id.pic);
        text = (TextView) root.findViewById(R.id.txt);
        smallImage = (ImageView) root.findViewById(R.id.small_pic);

        /*
        try {

            sv.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
                @Override
                public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                    Log.i("PicandVideo", "onSurfaceTextureAvailable");
                    if (!Utils.isEmpty(mediaPlayer)) {
                        Log.i("PicandVideo", "mediaPlayer is not null");
                        mSurface = new Surface(surface);
                        mediaPlayer.setSurface(mSurface);
                        play(filepath);
                    }

                    surfaceInited = true;

                }

                @Override
                public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

                }

                @Override
                public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                    if (!Utils.isEmpty(mediaPlayer)) {
                        mediaPlayer.setDisplay(null);
                    }
                    surfaceInited = false;
                    return false;
                }

                @Override
                public void onSurfaceTextureUpdated(SurfaceTexture surface) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
        */

        /*
        sv.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (!Utils.isEmpty(mediaPlayer)) {
                    mediaPlayer.setDisplay(holder);
                    play(filepath);
                }

                surfaceInited = true;

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (!Utils.isEmpty(mediaPlayer)) {

                    mediaPlayer.setDisplay(null);
                }
                surfaceInited = false;
            }
        });

         */
        sv.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                if (!Utils.isEmpty(mediaPlayer)) {
                    mediaPlayer.setDisplay(surfaceHolder);
                    play(filepath);
                }

                surfaceInited = true;

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                if (!Utils.isEmpty(mediaPlayer)) {

                    mediaPlayer.setDisplay(null);
                }
                surfaceInited = false;
            }
        });


        mWindowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
        Display display = mWindowManager.getDefaultDisplay();

        screenWidth = display.getWidth();
        screenHeight = display.getHeight();


        imageOptions = new ImageOptions.Builder()
                .setSize(screenWidth, screenHeight)
                .setImageScaleType(ImageView.ScaleType.FIT_XY).build();

        mSmallImgParams = (LayoutParams) smallImage.getLayoutParams();
        mTextParams = (LayoutParams) text.getLayoutParams();
    }

    PlayInterface playInterface = null;

    //回调接口
    public interface PlayInterface {
        void onCompletion();

        void onError(MediaPlayer mp, int what, int extra);

        void onPathError(Exception e);
    }

    public void setPlayInterface(PlayInterface playInterface) {
        this.playInterface = playInterface;
    }

    public void setMainHandler(PlayActivity.MainHandler handler) {
        mainHandler = handler;

    }

    public void playImageAndMp3(String imagepath, String mp3path) {
        loadImage(imagepath);
        playMp3(mp3path);
    }

    private void playMp3(String path) {
        Log.i("PicandVideo", "playMp3 path=" + path);
        initMediaPlayer();
        play(path);

    }

    public boolean isVideo(String path) {
        if (path.endsWith("mkv") || path.endsWith("mp4"))
            return true;
        else
            return false;
    }

    public void playMediaFile(String path) {
        filepath = path;

        if (isVideo(filepath)) {
            Log.i("PicandVideo", "playVideo filepath=" + filepath);
            initMediaPlayer();
            initSurfaceView(filepath);
        } else {
            Log.i("PicandVideo", "play pic filepath=" + filepath);
            loadImage(filepath);
            mainHandler.removeMessages(PlayActivity.PLAY_NEXT_FILE);
            mainHandler.sendEmptyMessageDelayed(PlayActivity.PLAY_NEXT_FILE, PlayActivity.getAutoPlayTime(mContext) * 1000);
        }
    }

    private void initMediaPlayer() {
        Log.i("PicandVideo", "initMediaPlayer");
        //pic.setVisibility(INVISIBLE);
        //text.setText("");

        if (!Utils.isEmpty(mediaPlayer)) {
            mediaPlayer.release();
            mediaPlayer = null;
        }

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.i("PicandVideo", "onPrepared");
                if (needSeekTime > 0 && mediaPlayer.getDuration() > needSeekTime)
                    mediaPlayer.seekTo(needSeekTime);

                mediaPlayer.start();
                Log.i("PicandVideo", "start play");
            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (!Utils.isEmpty(playInterface)) {
                    playInterface.onCompletion();
                }
                Log.i("PicandVideo", "onCompletion");
                //filepath = null;
                needSeekTime = -1;
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.i("PicandVideo", "onError");
                if (!Utils.isEmpty(mediaPlayer)) {
                    mediaPlayer.reset();
                }
                if (!Utils.isEmpty(playInterface)) {
                    playInterface.onError(mp, what, extra);
                }
                return true;
            }
        });
    }

    public void play(String path) {
        Log.i("PicandVideo", "play path=" + path);
        needSeekTime = -1;
        try {
            File file = new File(path);
            Log.i("PicandVideo", "play file=" + file);
            if (file != null && file.exists()) {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepareAsync();

                if (surfaceInited)
                    mediaPlayer.setSurface(mSurface);
            } else {
                playInterface.onPathError(new Exception("file is null error"));
            }
        } catch (Exception e) {
            playInterface.onPathError(new Exception(path + "\tfile is not find"));
            e.printStackTrace();
        }

    }

    public void pause() {
        Log.i("PicandVideo", "pause");

        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }

    }

    public void resume() {
        Log.i("PicandVideo", "resume");

        if (mediaPlayer != null) {
            mediaPlayer.start();
        }

    }

    public int getPlayTime() {
        Log.i("PicandVideo", "getPlayTime");

        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            return mediaPlayer.getCurrentPosition();
        }

        return 0;
    }

    public int getPlayLeftTime() {
        Log.i("PicandVideo", "getPlayTime");

        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            return mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition();
        } else if (mediaPlayer != null) {
            return mediaPlayer.getDuration();
        }

        return 0;
    }

    public void insertPicture(String picPath) {

        File file = new File(picPath);
        if (file.exists()) {
            Log.i("PicandVideo", "insertPicture " + picPath);

            x.image().loadDrawable(picPath, imageOptions, new Callback.CommonCallback<Drawable>() {
                @Override
                public void onSuccess(Drawable result) {
                    pic.setImageDrawable(result);
                    pic.setVisibility(VISIBLE);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.i("PicandVideo", "onError");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    Log.i("PicandVideo", "onCancelled");
                }

                @Override
                public void onFinished() {
                    Log.i("PicandVideo", "onFinished");
                }
            });

        } else {
            Log.i("PicandVideo", "insertPicture onPathError ");
            playInterface.onPathError(new IOException(picPath + "File is not exists"));
        }
    }

    public void clearPicture() {
        Log.i("PicandVideo", "clearPicture");
        pic.setVisibility(INVISIBLE);
        pic.setImageResource(0);
    }

    private void initSurfaceView(final String path) {
        iv.setVisibility(INVISIBLE);

        Log.i("PicandVideo", "initSurfaceView surfaceInited=" + surfaceInited);

        sv.setVisibility(INVISIBLE);
        sv.setVisibility(VISIBLE);

        /*if (surfaceInited) {
            play(path);
        } else {
            sv.setVisibility(INVISIBLE);
            sv.setVisibility(VISIBLE);
        }*/
    }

    public void stopPlay() {
        Log.i("PicandVideo", "stopPlay");

        iv.setImageResource(0);

        if (!Utils.isEmpty(mediaPlayer)) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void seek(int seekTime) {
        if (filepath != null && filepath.contains(".mp4")) {
            if (mediaPlayer.isPlaying() && mediaPlayer.getDuration() > seekTime) {
                mediaPlayer.seekTo(seekTime);
            } else {
                needSeekTime = seekTime;
            }
        } else {
            Log.i("PicandVideo", "can not seek now!");
        }
    }


    private void loadImage(String imagepath) {
        surfaceInited = false;
        sv.setVisibility(INVISIBLE);
        iv.setVisibility(VISIBLE);
        File file = new File(imagepath);
        if (file.exists()) {

            x.image().loadDrawable(imagepath, imageOptions, new Callback.CommonCallback<Drawable>() {
                @Override
                public void onSuccess(Drawable result) {
                    iv.setImageDrawable(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

            //Glide.with(this).load(file).into(iv);
        } else {
            Log.i("PicandVideo", "loadImage onPathError ");
            playInterface.onPathError(new IOException(imagepath + "File is not exists"));
        }
    }


    public void setDisplayText(int size, int x, int y, int color, String str) {
        Log.i("PicandVideo", "size= " + str);
        Log.i("PicandVideo", "x= " + x);
        Log.i("PicandVideo", "y= " + y);
        Log.i("PicandVideo", "screenWidth= " + screenWidth);
        Log.i("PicandVideo", "screenHeight= " + screenHeight);
        text.setText(str);

        text.setTextSize(size);
        text.setTextColor(color);

        int _x = (int) (screenWidth / 265.0f * x);
        int _y = (int) (screenHeight / 265.0f * y);
        Log.i("PicandVideo", "_x= " + _x);
        Log.i("PicandVideo", "_y= " + _y);
        mTextParams.leftMargin = _x;
        mTextParams.topMargin = _y;
        text.setLayoutParams(mTextParams);
    }

    public void setSmallImageLocation(int x, int y, int imgW, int imgH) {
        int _x = 0, _y = 0;
        if (x == -1 && y == -1) {
            _x = (screenWidth - imgW) / 2;
            _y = (screenHeight - imgH) / 2;
        } else {
            _x = (int) (screenWidth / 265.0f * x);
            _y = (int) (screenHeight / 265.0f * y);

            if (_x + imgW > screenWidth)
                _x = screenWidth - imgW;

            if (_y + imgH > screenHeight)
                _y = screenHeight - imgH;

            Log.i("PicandVideo", "_x= " + _x);
            Log.i("PicandVideo", "_y= " + _y);
        }

        mSmallImgParams.leftMargin = _x;
        mSmallImgParams.topMargin = _y;
        smallImage.setLayoutParams(mSmallImgParams);
    }

    public void hideSmallImage() {
        smallImage.setImageResource(0);
        smallImage.setVisibility(INVISIBLE);
    }

    public void showSmallImage(String imagepath, final int _x, final int _y) {
        smallImage.setVisibility(VISIBLE);
        File file = new File(imagepath);
        if (file.exists()) {

            x.image().loadDrawable(imagepath, imageOptions, new Callback.CommonCallback<Drawable>() {
                @Override
                public void onSuccess(Drawable result) {
                    smallImage.setImageDrawable(result);
                    setSmallImageLocation(_x, _y, result.getIntrinsicWidth(), result.getIntrinsicHeight());
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        } else {
            playInterface.onPathError(new IOException(imagepath + "File is not exists"));
        }
    }

}
